const getUrlParams = (url, params) => {
  if (params && Object.keys(params).length > 0) {
    return url + "?" + Object.keys(params).map(function (key) {
      return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
    }).join("&");
  } else {
    return url
  }
}

var releasePageStack = (url) => {
  let pages = getCurrentPages()
  for (let i = 0; i < pages.length; i++) {
    if (getUrlParams(`/${pages[i].route}`, pages[i].options) === url) {
      return pages.length - (i + 1)
    }
  }
  if (pages.length >= 10) {
    return -2
  } else {
    return -1
  }
}

const push = (url) => {
  let delta = releasePageStack(url)
  if (delta === -1) {
    wx.navigateTo({
      url: url
    })
  } else if (delta === -2) {
    wx.redirectTo({
      url: url
    })
  } else {
    wx.navigateBack({
      delta: delta
    })
  }
}

module.exports = {
  push: push
}